<template>
  <div class="menu-link-lib">
    <!--按钮组-->
    <div class="Btns-ctrl-body btns-under-box">

      <!--高级搜索-->
      <SearchPublic
        :searchObj="searchObj"
        @searchParams="searchParamsFn"
        v-show="ajaxSearchType !== 2"
      ></SearchPublic>

<!--      <div class="search-ctrl f-l " v-if="ajaxSearchType != 2">
        <input type="text" class="search-text" placeholder="搜索菜单名称" v-model="searchStr">
        <button type="button" class="search-btn btn btn-info" @click="btnSearch(pageSize, 0)">搜索</button>
      </div>-->

      <div class="btns f-r">
        <button type="button" v-if="ajaxSearchType == 2"
          class="btn btn-info"
          @click="btnProgram" >
          方案库
        </button>
        <button type="button" v-if="ajaxSearchType == 2"
          class="btn btn-info"
          @click="btnPreviewProgram" >
          预览
        </button>
        <button type="button"
          class="btn btn-info"
          @click="btnAdd" >
          新增
        </button>
        <button type="button"
          class="btn btn-warning"
          @click="btnRevise" >
          修改
        </button>
        <button type="button"
          class="btn btn-danger"
          @click="btnDelete" >
          删除
        </button>
      </div>
    </div>
    <!--按钮组闭合-->
    <div class="wrapper">
     <!-- tree-table-gride -->
      <div class="zk-talbe">
        <zk-table
          ref="table"
          sum-text="sum"
          index-text="#"
          :data="dataMenuList"
          :columns="columns"
          :stripe="props.stripe"
          :border="props.border"
          :show-header="props.showHeader"
          :show-summary="props.showSummary"
          :show-row-hover="props.showRowHover"
          :show-index="props.showIndex"
          :tree-type="props.treeType"
          :is-fold="props.isFold"
          :expand-type="props.expandType"
          :selection-type="props.selectionType"
          :row-class-name="'row-class-name'"
          @row-click = rowClick >
          <!-- <template slot="$expand" scope="scope">
            {{ `My name is ${scope.row.name},
              this rowIndex is ${scope.rowIndex}.`
            }}
          </template> -->
          <!-- <template slot="likes" scope="scope">
            {{ scope.row.likes.join(',') }}
            <img :src="require('@/assets/logo.png')" :data-scope="scope.row.name" style="width: 20px;" />
          </template> -->
          <template slot="displayName" slot-scope="scope">
            {{ scope.row.displayName }}
            <img :src="PicSrc(scope)"
              :onerror="PicErr" :data-id="scope.row.id" class="menu-img"  />
          </template>

        </zk-table>
      </div>
      <!-- 分页 -->
      <!--<pages class="pages"-->
        <!--v-if="ajaxSearchType == 2"-->
        <!--:showItem = showItem-->
        <!--:allpage = allpage-->
        <!--:pageSize = pageSize-->
        <!--:allDataSum = allDataSum-->
        <!--@current-change = currentChange >-->
      <!--</pages>-->
      <!-- 分页闭合 -->
    </div>
    <!-- tree table关闭 -->
    <!-- 弹框 -->
    <vdialog :dialogToggle = dialogToggle
      @btnConfirm = Confirm >
      <template slot="dialogHeader" >
        <p v-text="dialogTitle"></p>
        <!-- <h4 v-show="dialogType == 'add'" v-text="'父级菜单名称：'+parentDisplayName"></h4> -->
      </template>

      <template slot="dialogBody" >
          <div class="even-row">
            <div class="modal-row" >
              <div class="modal-form-key f-l indispensable" v-text="dialogInputLabel.inputName" ></div>
              <input class="modal-text f-l" type="text" v-model="input_Name" required="required" >
            </div>
            <div class="modal-row" >
              <div class="modal-form-key f-l indispensable" v-text="dialogInputLabel.inputDisplayName"></div>
              <input class="modal-text f-l" type="text" v-model="input_displayName" required="required" >
            </div>
            <div class="modal-row" v-show="ajaxSearchType != 1 && programToggle" >
              <div class="modal-form-key f-l indispensable" v-text="dialogInputLabel.selectTarget"></div>
              <select v-model="select_target" :disabled="ajaxSearchType == 1" :class="{'select-disabled':ajaxSearchType == 1}" >
                <option v-for="option in optTarget" :key="option" v-text="option"></option>
              </select>
            </div>
            <div class="modal-row" >
              <div class="modal-form-key f-l indispensable" v-text="dialogInputLabel.inputSort"></div>
              <input class="modal-text f-l dialog-number" type="number" min="0" v-model.number="input_sort" required="required" >
            </div>
            <div class="modal-row" v-show="ajaxSearchType != 1" >
              <div class="modal-form-key f-l indispensable" v-text="dialogInputLabel.selectType" ></div>
              <select v-model="select_type" :disabled="selectTypeDisabled" :class="{'select-disabled':selectTypeDisabled}" >
                <option v-for="option in optType" :key="option" v-text="option"></option>
              </select>
            </div>
            <div class="modal-row" >
              <div class="modal-form-key f-l" >备注：</div>
              <input class="modal-text f-l" type="text" v-model="textarea_remark" >
            </div>
            <div class="modal-row " v-if="ajaxSearchType != 1 && programToggle" >
              <div class="modal-form-key f-l">链接：</div>
              <input class="modal-text f-l" type="text" disabled v-model="linkConfirmObj.name" >
            </div>
            <div class="modal-row " v-if="ajaxSearchType != 1 && programToggle" >
              <div class="modal-form-key f-l">
                <button type="button"
                        class="btn btn-info btn-pic-link-dialog"
                        @click="dialogBtnLibConfirm('link')" >
                  选择
                </button>
                <button type="button"
                        class="btn btn-info btn-pic-link-dialog"
                        @click="dialogBtnLibCancel('link')" >
                  清除
                </button>
              </div>
            </div>
            <div class="modal-row " v-if="ajaxSearchType != 1 && programToggle" >
              <div class="modal-form-key f-l">图片：</div>
              <input class="modal-text f-l" type="text" disabled v-model="picConfirmObj.name" >

            </div>
            <div class="modal-row" v-if="ajaxSearchType != 1 && programToggle" >
              <div class="modal-form-key f-l">
                <button type="button"
                        class="btn btn-info btn-pic-link-dialog"
                        @click="dialogBtnLibConfirm('pic')" >
                  选择
                </button>
                <button type="button"
                        class="btn btn-info btn-pic-link-dialog"
                        @click="dialogBtnLibCancel('pic')" >
                  清除
                </button>
              </div>
            </div>

          </div>
      </template>
    </vdialog>
    <vdialog :dialogToggle = picLibToggle
      @btnConfirm = metaConfirm >
      <template slot="dialogHeader" >
        <h3 >从图片库选择：</h3>
      </template>
      <template slot="dialogBody">
         <picLib
           :isDeleteBtn="false"
           ref="dialog_pic_lib" style="height: 300px;"></picLib>
      </template>
    </vdialog>
    <vdialog :dialogToggle = linkLibToggle
      @btnConfirm = metaConfirm >
      <template slot="dialogHeader" >
        <h3 >从链接库选择：</h3>
      </template>
      <template slot="dialogBody">
         <linkLib
           :isDeleteBtn="false"
           ref="dialog_link_lib" style="height: 300px;"></linkLib>
      </template>
    </vdialog>
      <msgDialog :dialogInit = msgDialogInit
      :dialogIsShow = msgDialogIsShow ></msgDialog>
    <isRealDialog :dialogInit = isRealDialogInit
      :dialogIsShow = isRealDialogShow
      @confirm = realDelete ></isRealDialog>
  </div>
</template>

<script>
import vdialog from 'sudoku/atom/vdialog'
import mustChoseIcon from 'sudoku/atom/mustChoseIcon'
import pages from 'sudoku/atom/pages';
import picLib from 'sudoku/mateLib/PicLib'
import linkLib from 'sudoku/mateLib/LinkLib'
import msgDialog from 'sudoku/atom/msgDialog';
import isRealDialog from 'sudoku/atom/isRealDialog';
import { searchMenu, addMenu, updateMenu, deleteMenu, getNodeChildById } from '@/api/menu'
import SearchPublic from "../../publicTemplate/search/SearchPublic"
var ajaxTypeMenu = 0;
var ajaxTypeDataObject = 1;
var ajaxTypeProgram = 2;

export default {
  name: 'menuLinkLib',
  props: {

    dataProgramItem: String
  },
  data() {
    return {
      props: {
        stripe: true,        //是否显示间隔斑马纹
        border: true,        //是否显示纵向边框
        showHeader: true,    //是否显示表头
        showSummary: false,  //是否显示表尾合计行
        showRowHover: true,  //鼠标悬停时，是否高亮当前行
        showIndex: true,     //是否显示数据索引
        treeType: true,      //是否为树形表格
        isFold: true,        //树形表格中父级是否默认折叠
        expandType: false,   //是否为展开行类型表格
        selectionType: false  //是否为多选类型表格
      },
      columns: [            //列表头部信息
        {
          label: '菜单code',
          prop: 'name',
          width: '300px',
        },
        {
          label: '名称',
          prop: 'displayName',
          minWidth: '250px',
          type: 'template',
          template: 'displayName',
        },
        {
          label: '菜单类型',
          prop: 'target',
        },
        {
          label: '备注',
          prop: 'remark',
          minWidth: '200px',
        },
      ],
      ajaxSearchType: 0, // 0 菜单 1 数据权限 2 方案

      isRealDialogInit: {       //删除的时候确认弹框
          'title': '请确认删除',
          'content': ''
        },
      isRealDialogShow: false,
      realDeleteData: [],   //存放删除ajax的数据

       msgDialogInit: {        //按钮操作结果消息弹框
          'title': '',
          'content': '',
          'btns': []
        },
        msgDialogIsShow: false,

      dataMenuList: [],         //表格初始化数据

      PicErr: 'this.src="' + require('@/assets/error.png') + '"',  //img加载失败的图片

      showItem: 10,       //分页条下面item的数目
      allpage: 0,         //根据每页数据/总数据得到的总页数
      pageSize: 6,       //每页数据
      allDataSum: 0,      //总数据

      searchStr: '',           //搜索的输入框字段
      dialogToggle: false,       //弹窗显示控制字段

      checkedAry: [],              //表单选中的index数组

      checkedItem: [],           //点击选中的值存放处

      rowEventList: [],               //存放点中的事件

      dialogInputLabel: {
        "inputName": '菜单code：',
        "inputDisplayName": '菜单显示名称：',
        "selectTarget": '菜单目标：',
        "inputSort": '菜单排序：',
        "selectType": '菜单方案类型：'
      },
      dialogTitle: '新增菜单',
      pid: '',        //父菜单id
      parentDisplayName: '无',
      dialogType: '',            //用来存放弹窗的类型，add 新增； update 修改
      //弹窗数据
      input_Name: '',            //新建菜单名称
      input_displayName: '',     //新建菜单显示名称
      select_target: '',        //菜单目标选择值
      optTarget: ['resource','exe','img','html','menu'],        //菜单目标可选的值
      input_sort: 0,            //菜单排序
      select_type: '',           //菜单类型选择值
      optType: ['缺省', '九宫格', '十宫格', '地图'],               //菜单类型可选的值
      textarea_remark: '',         //备注

      picLibToggle: false,          //图片弹窗的控制标志
      linkLibToggle: false,          //链接弹窗的控制标志

      picOrLink: '',
      /**
        createTime: "2018-06-29T02:03:00.0000000+08:00"
        createUserId: "test-renwei"
        id: "700f67e8-5133-4ae2-a162-5b4aa4317ce7"
        name: "综合态势看板"
        storeId: "60e70655-9099-4cfc-92f9-7fa3f3ee69b3"
        updateTime: null
        updateUserId: null
       */
      picConfirmObj: {
        "name": '未选择',
        "id": ''
      },        //从图片库中选中的图片数据
      /**
        createTime: "2018-08-14T09:11:30.0000000+08:00"
        createUserId: "zhoupeng"
        id: "9aaf01f2-1546-4bac-9833-cb997d45d9af"
        name: "12"
        updateTime: "2018-08-15T14:13:10.0000000+08:00"
        updateUserId: "zhoupeng"
        url: "12"
       */
      linkConfirmObj: {
        "name": '未选择',
        "id": ''
      },        //从链接库中选中的图片数据
      msgDialogInit: {        //按钮操作结果消息弹框
        'title': '',
        'content': '',
        'btns': []
      },
      msgDialogIsShow: false,

      MenuTyepFlag: false,        //标记是否需要从父级获取菜单方案类型
      previewId: '',           //预览和维护使用的id
      searchObj:{
        condition:[
          {"title":"名称","key":"name",'type':'text',"value":'','data':''},
        ],
        htmlType:"searchDefaultPublic",
      },
      isLock: false // 避免多次点击重复数据
    }
  },
  computed: {
    programToggle() {
      //只有修改根方案才隐藏一部分选项
        if(this.checkedItem[0] != undefined && this.dialogType == 'update' && this.checkedItem[0]['pid'] == null && this.ajaxSearchType == ajaxTypeProgram ){ // 修改 && pid == null && this.ajaxSearchType == 2(方案)
          this.optType = [ '九宫格', '十宫格' ];
          return false;
        }
        else {
          return true;
        }
    },
    selectTypeDisabled(){ // 是否可以选择type字段
      if((this.ajaxSearchType == ajaxTypeProgram && this.dialogType == 'add') | (this.checkedItem[0] != undefined && this.checkedItem[0]['pid'] != null && this.dialogType == 'update') | (this.checkedItem[0] != undefined && this.dialogType == 'add')){ //不能选 1.是方案库然后是新增（方案库修改根菜单可以） 2. 不是父菜单
        return true
      }
      else {
        return false
      }
    }
  },
  methods: {
    //搜索
    searchParamsFn(searchParams){
      //console.log(this.searchObj.condition);
      this.searchStr = this.searchObj.condition[0].value;
      this.btnSearch(-1,0)
    },
    /**
     * 只有新建根菜单才可以选择菜单方案类型，修改和新建子菜单方案类型为父级类型
     */
    showMenuTyep() {
      if(this.dialogType == 'add' && this.pid == null){ //为新建并且是根菜单
        this.MenuTyepFlag = false;
        return false;
      }
      else {
        this.MenuTyepFlag = true;
        return true;
      }
    },
    /**
     * 返回文件服务的地址
     */
    PicSrc(scope) {
      if(scope != null && scope.row != null
        && scope.row.imgModel != null
        && scope.row.imgModel.storeId != null){
        let storeId = scope.row.imgModel.storeId
        return baseURL                                          //运行环境
          + 'api/jp-TIFS-FileCenter-ms/file?businessId='  //微服务地址
          + storeId
      }
    },
    currentChange(current) {
      /**
       * current为分页组件传递过来的当前页,后台分页是从第0页开始
       */
      this.btnSearch(this.pageSize, current - 1);
      //分页事件发生的时候要清空保存选中的数组
      //清除样式
      this.clearFn();
      this.checkedItem = [];//数据
    },
    btnSearch(pageSize, current) {
      let data = {
        'name': this.searchStr,
        'curPage': current,
        'pageSize': pageSize,
        'type': this.ajaxSearchType,
      };
      this.$axios.get(this.HOST+'/menu/queryByName?name='
        + data.name
        + '&curPage='
        + data.curPage
        + '&pageSize='
        + data.pageSize
        + '&type='
        + data.type).then( res => {
        let data = res.data;
        let count = res.data.count;           //总数据量
        this.allpage = Math.ceil(count/this.pageSize);
        this.allDataSum = count;
        this.dataMenuList = data.menuList;
      })
      /*searchMenu(data).then( res => {
        let data = res.data;
        let count = res.data.count;           //总数据量
        this.allpage = Math.ceil(count/this.pageSize);
        this.allDataSum = count;
        this.dataMenuList = data.menuList;
      })*/
    },
//    跳转到方案页面
    btnProgram() {
      this.$router.push({name:'programLib'})
    },
//    跳转到预览页面
    btnPreviewProgram() {
      this.$router.push({name:'previewProgram', params:{previewId:this.dataMenuList[0].id}})
    },
    btnAdd() {
      this.addOrRevise('add');
    },
    btnRevise() {
      this.addOrRevise('update');
    },
    btnDelete() {
      //console.log(this.checkedItem);
      if(this.checkedItem.length > 0){
        let data = [];
        for(let i = 0; i < this.checkedItem.length; i++){
          let item = this.checkedItem[i];
          if(item.children == null){
            data.push(item.id);
          }
          else {
            this.s_alert(item.name+'有子菜单不能删除');
            // this.dialogMSG(item.name+'有子菜单不能删除', 3000);
            // alert(item.name+'有子菜单不能删除');
            this.refreshPage();
            return;
          }
        }
        this.isRealDialogShow = !this.isRealDialogShow;
        this.realDeleteData = data;
        // deleteMenu(data).then( res => {
        //   this.dialogMSG('删除成功', 1000);
        //   // alert('删除成功');
        //   this.refreshPage();
        // })
      }
      else {
        this.s_alert('请选择要删除的项');
        // this.dialogMSG('请选择要删除的项', 3000);
        // alert('请选择要删除的项');
      }

    },
    realDelete() {
      // 如果删除的是最顶方案，就要跳转出本页面
      this.$axios({
        url:this.HOST+'/menu/delete',
        method:'post',
        headers: {'content-type': 'application/json;charset=UTF-8'},
        data: this.realDeleteData,
      })
        .then( res => {
        if(this.realDeleteData[0] === this.previewId){
          this.btnProgram();
        }else {
          // alert('删除成功');
          this.s_alert('删除成功!');
          // this.dialogMSG('删除成功', 1000);
          this.refreshPage();
          if (this.ajaxSearchType == ajaxTypeDataObject) {
            this.s_logwrite("宫格配置-数据权限","删除");
          }else if (this.ajaxSearchType == ajaxTypeMenu) {
            this.s_logwrite("宫格配置-菜单管理","删除");
          }else if (this.ajaxSearchType == ajaxTypeProgram) {
            this.s_logwrite("宫格配置-方案库维护","删除");
          }
        }
      })
        .catch( err => {
          this.s_alert("删除失败！");
          //console.log(err)
        })
     /* deleteMenu(this.realDeleteData).then( res => {
        this.dialogMSG('删除成功', 1000);
        // alert('删除成功');
        this.refreshPage();
      })*/
    },
// 点击新增或者修改按钮事件
    addOrRevise (str){
      let length = this.checkedItem.length;
      if( length > 0 ) {    //有勾选项
  /**
    children: null
    displayName: "测试方案3"
    id: "fc199892-0942-40ab-95bf-440c3770950b"
    name: "测试方案1"
    pid: null
    remark: "string"
    sort: 2
    target: "menu"
    type: "WPF_9"
  imgModel: Object
    createTime: "2018-07-10T17:38:10.0000000+08:00"
    createUserId: "2BCC5C5D-3B9A-4D8C-AC91-FD8CD2529B6E"
    id: "1830612b-a986-4183-9d79-46ec91786a88"
    name: "十宫格预览"
    storeId: "1098c819-84f0-4de8-bfd0-412a7861c0c0"
    updateTime: null
    updateUserId: null
  linkModel: Object
    createTime: "2018-08-13T19:11:40.0000000+08:00"
    createUserId: "zhoupeng"
    id: "cabffee4-cac7-4f88-bac3-bb18792632ff"
    name: "6"
    updateTime: null
    updateUserId: null
    url: "6"
  */
        let item = this.checkedItem[length - 1];
        if( str == 'update' && this.ajaxSearchType == ajaxTypeDataObject && item.target != 'dataobject' ){  //数据权限页面
          this.s_alert('选择的数据项target值不是dataobject');
          // this.dialogMSG('选择的数据项target值不是dataobject', 1500);
          return;
        }
        //
        else {
          switch(str){
            case 'add':
              this.pid = item.id;   //新增在选中项的下一层
              this.select_type = this.switchFn(item.type);
              if(this.ajaxSearchType == ajaxTypeDataObject){
                this.dialogTitle = '新增数据权限';
              }
              else if(this.ajaxSearchType == ajaxTypeMenu){
                this.dialogTitle = '新增菜单';
              }
              else if(this.ajaxSearchType == ajaxTypeProgram){
                this.dialogTitle = '新增方案';
              }
              break;
            case 'update':          // 修改只有选中后才开始
              this.pid = item.pid;   //修改页面
              //图片是否为空
              if(item.imgModel != null) {
                this.picConfirmObj = item.imgModel;
              }
              else {
                this.picConfirmObj.name = '未选择';
                this.picConfirmObj['id'] = '';
              }
              //链接是否为空
              if(item.linkModel != null) {
                this.linkConfirmObj = item.linkModel;
              }
              else {
                this.linkConfirmObj.name = '未选择';
                this.linkConfirmObj['id'] = '';
              }
              if(this.ajaxSearchType == ajaxTypeDataObject){
                this.dialogTitle = '修改数据权限';
              }
              else if(this.ajaxSearchType == ajaxTypeMenu){
                this.dialogTitle = '修改菜单';
              }
              else if(this.ajaxSearchType == ajaxTypeProgram){
                this.dialogTitle = '修改方案';
              }
              this.input_Name = item.name;
              this.input_displayName = item.displayName;
              this.textarea_remark = item.remark;
              this.input_sort = item.sort;
              this.select_target = item.target;
              this.select_type = this.switchFn(item.type);
              this.dialogType = 'update';           //修改弹窗类型为修改
              this.dialogToggle = !this.dialogToggle;
          }
        }
      }
      else { // 没有选择某项
        if( str == 'add' ){
          switch(this.ajaxSearchType){
            case ajaxTypeMenu:   //为新建根菜单
              this.pid = null;
              break;
            case ajaxTypeProgram:   //为方案新建
              this.pid = this.dataMenuList[0].id;
              this.select_type = this.switchFn(this.dataMenuList[0].type);
              break;
            case ajaxTypeDataObject:    //数据权限新建根,能新建根菜单
              this.pid = null;
              break;
          }
        }
        else if(str == 'update'){
          return;
        }
      }
      // 组合弹窗显示数据
      switch(str){
        case 'add':
          this.dialogType = 'add';  //更改弹窗类型为新增，这样按钮的事件变成新增的
          this.dialogToggle = !this.dialogToggle; //取反显示弹窗
          this.picConfirmObj.name = '未选择';
          this.linkConfirmObj.name = '未选择';
          this.input_displayName = '';
          this.picConfirmObj['id'] = '';
          this.linkConfirmObj['id'] = '';
          this.input_Name = '';
          this.textarea_remark = '';
          this.input_sort = 0;
          if(this.ajaxSearchType == ajaxTypeDataObject){    //数据权限页面不能选择target,默认都是dataobject
            this.select_target = 'dataobject';
            this.optTarget = ['dataobject'];        //菜单目标可选的值
            this.dialogTitle = '新增数据权限';
          }
          else if(this.ajaxSearchType == ajaxTypeMenu){
            this.select_target = '';
            this.dialogTitle = '新增菜单';
          }
          else if((this.ajaxSearchType == ajaxTypeProgram)){
            this.select_target = '';
            this.dialogTitle = '新增宫格菜单';
          }
          break;
      }
    },
    rowClick(row, rowIndex, event) {   // 表格行点击事件
      this.clearFn();//变成单选，但是数据还是多选的
      //2为通过template上img的自定义属性data-id获取id然后对数据进行操作
      let id = row.currentTarget.childNodes[2].getElementsByTagName('img')[0].getAttribute('data-id');

      //先判断this.checkedItem中是否有点击的id如果有就删除并且移走class，没有就添加
      let ischecked = this.toggleJSON(this.checkedItem, 'id', id);
      if(ischecked) {//true取消选择，undefined选择
        this.checkedRemoveClass(row)
      }
      else {
        //点击数据保存到数组的方法 this.checkedItem用来存放点击项的数据
        this.aryFindChildre(this.dataMenuList, 'id', id)
        this.checkedAddClass(row)
      }
       // 数据要变成一条数据
      if(this.checkedItem.length > 0){
        let ary = [];
        ary.push(this.checkedItem.pop());
        this.checkedItem = ary;
      }
      //console.log(this.checkedItem)
    },
    /* * 素材页面选择按钮点击事件
    * @param: str 'pic' 图片 'link' 素材
    */
    dialogBtnLibConfirm(str) {
      this.picOrLink = str;
      this[`${str}LibToggle`] = !this[`${str}LibToggle`];
    },
    dialogBtnLibCancel(str) {
      this[`${str}ConfirmObj`] = {
        "name": '未选择',
        "id": ''
      };
    },
    metaConfirm() {//从图片库选择，从链接库选择，确认按钮事件
      let some = this.picOrLink;
      let data = this.$refs[`dialog_${some}_lib`].checkedPicAry; //这是所有选中项存放的数组
      let dataLength = data.length;
      if(dataLength) {
        this[`${some}ConfirmObj`] = data[dataLength - 1];
        this[`${some}LibToggle`] = !this[`${some}LibToggle`];
      }
      //console.log(this[`${some}ConfirmObj`]);
    },
    Confirm() { //弹窗确认按钮事件
      if (this.isLock) {
        return true
      }
      this.isLock = true // 锁住
      //console.log(this.isLock);
      let select_type = '';
      select_type = this.switchFn(this.select_type);
      if(this.ajaxSearchType == ajaxTypeDataObject){ //如果是数据权限页面type默认是‘DATA’
        select_type = 'DATA';
      }
      if(this.input_Name == '' | this.input_displayName == '' | this.select_target == ''){
        this.s_alert('请填写带有*号的项');
        this.isLock = false // 解锁
        return
      } else if (!(/^[0-9]+$/.test(this.input_sort))) {
        this.s_alert('请正确填写排序')
        this.isLock = false // 解锁
        return
      }
      debugger
      let data = {
        "pid": this.pid,
        "displayName": this.input_displayName,
        "image": this.picConfirmObj.id,
        "uri": this.linkConfirmObj.id,
        "name": this.input_Name,
        "remark": this.textarea_remark,
        "sort": this.input_sort,
        "target": this.select_target,
        "type": select_type,
      }
      if(this.dialogType == 'add') {
        this.$axios({
          url:this.HOST+'/menu/add',
          method:'post',
          headers: {'content-type': 'application/json;charset=UTF-8'},
          data:JSON.stringify(data)
        })
          .then(res => {
            setTimeout(() => {
              this.isLock = false // 解锁
            },200)
          this.dialogToggle = !this.dialogToggle;
          this.s_alert('新增成功!');
          // this.dialogMSG('新增成功', 1000);
          if (this.ajaxSearchType == ajaxTypeDataObject) {
            this.s_logwrite("宫格配置-数据权限","新增");
          }else if (this.ajaxSearchType == ajaxTypeMenu) {
            this.s_logwrite("宫格配置-菜单管理","新增");
          }else if (this.ajaxSearchType == ajaxTypeProgram) {
            this.s_logwrite("宫格配置-方案库维护","新增");
          }
          // alert('新增成功');
          this.refreshPage();
        })
          .catch(err => {
            setTimeout(() => {
              this.isLock = false // 解锁
            },200)
            this.s_alert('新增失败！');
            //console.log(err);
          })
        /*addMenu(data).then(res => {
          this.dialogToggle = !this.dialogToggle;
          this.dialogMSG('新增成功', 1000);
          // alert('新增成功');
          this.refreshPage();
        });*/
      }
      else if(this.dialogType == 'update') {
        this.checkedItem = [this.checkedItem.pop()];
        data['id'] = this.checkedItem[0].id;//选中最后一项的id
        //console.log(data['id']);
        this.$axios({
          url:this.HOST+'/menu/update',
          method:'post',
          headers: {'content-type': 'application/json;charset=UTF-8'},
          data:JSON.stringify(data)
        })
          .then( res => {
            setTimeout(() => {
              this.isLock = false // 解锁
            },200)
          this.dialogToggle = !this.dialogToggle;
          this.s_alert('修改成功！');
          // this.dialogMSG('修改成功', 1000);
          if (this.ajaxSearchType == ajaxTypeDataObject) {
            this.s_logwrite("宫格配置-数据权限","修改");
          }else if (this.ajaxSearchType == ajaxTypeMenu) {
            this.s_logwrite("宫格配置-菜单管理","修改");
          }else if (this.ajaxSearchType == ajaxTypeProgram) {
            this.s_logwrite("宫格配置-方案库维护","修改");
          }
          // alert('修改成功');
          this.refreshPage();
        })
          .catch( err => {
            setTimeout(() => {
              this.isLock = false // 解锁
            },200)
            this.s_alert("修改失败！");
            //console.log(err);
          })
        /*updateMenu(data).then( res => {
          this.dialogToggle = !this.dialogToggle;
          this.dialogMSG('修改成功', 1000);
          // alert('修改成功');
          this.refreshPage();
        })*/
      }
      //console.log(JSON.stringify(data));
    },
    switchFn(origin){
      switch(origin){
        case 'DEFAULT':
          return '缺省';
          break;
        case 'WPF_9':
          return '九宫格';
          break;
        case 'WPF_10':
          return '十宫格';
          break;
        case 'MAP':
          return '地图';
          break;
        case '缺省':
          return 'DEFAULT';
          break;
        case '九宫格':
          return 'WPF_9';
          break;
        case '十宫格':
          return 'WPF_10';
          break;
        case '地图':
          return 'MAP';
          break;
      }
    },
    // 暴力的清除样式和存放点击事件的数据
    clearFn() {
      let backgroundImageLength = document.getElementsByClassName('zk-table__cell-inner').length
      let colorLength = document.getElementsByClassName('zk-table__body-row').length
      for(let i = 0; i < backgroundImageLength; i++) {
        document.getElementsByClassName('zk-table__cell-inner')[i].style.background = '';
      }
      for(let i = 0; i < colorLength; i++) {
        document.getElementsByClassName('zk-table__body-row')[i].style.color = '#000';
        document.getElementsByClassName('zk-table__body-row')[i].style.background = '#fff';
      }
    },
    //刷新页面
    refreshPage() {
      this.clearFn();// 清除选中的样式
      this.checkedItem = [];//数据
      switch(this.ajaxSearchType){
        case ajaxTypeMenu://菜单
        case ajaxTypeDataObject://
          this.btnSearch(-1, 0); // 重新执行一遍初始化操作 -1查全部
          break;

        case ajaxTypeProgram://方案
        //通过传入数据的this.dataMenuList[0].id来专门的id接口查询
          this.$axios.get(this.HOST+'/menu/getNodeChildById?id='
            + this.dataMenuList[0].id).then( res => {
            let ary = [];
            ary.push(res.data)
            this.dataMenuList = ary;
          }); // 重新执行一遍初始化操作
          break;
          /*getNodeChildById(this.dataMenuList[0].id)
          .then( res => {
            let ary = [];
            ary.push(res.data)
            this.dataMenuList = ary;
          }); // 重新执行一遍初始化操作
          break;*/
      }
    },
    //判断json数据中是否有某个相等的值
    toggleJSON(ary, attr, value) {
      for(let i = 0; i < ary.length; i++){
        if(ary[i][attr] == value) {//相等就删除，代表取消选择
          ary.splice(i, 1)
          return true;
        }
      }
    },
    //判断是否有相等的，如果有就返回相等的项
    equalJSONAttr(ary, attr, value) {
      for(let i = 0; i < ary.length; i++){
        if(ary[i][attr] == value) {//相等就删除，代表取消选择
          return ary[i];
        }
      }
    },

    //选中增加选中样式
    checkedAddClass(row) {
      row.currentTarget.style.color = '#fff';
      row.currentTarget.style.background = '#009aff' ;
//      row.currentTarget.children[0].children[0].style.background = 'url('+ require('@/assets/true.png')+') no-repeat' ;
    },
    //取消选中样式
    checkedRemoveClass(row) {
      row.currentTarget.style.color = '#000';
      row.currentTarget.style.background = '#fff' ;
      row.currentTarget.children[0].children[0].style.background = '' ;
    },
    /**
     * ary 需要遍历的数组， attr需要对比的值 id对比的值
     * this.checkedItem 全局变量存放数据
     */
    aryFindChildre( ary, attr , id) {
      const self = this;
      if(ary != null) {
        for(let i = 0; i < ary.length; i++){
          if(ary[i][attr] === id) {// 递归终止条件
            self.checkedItem.push(ary[i]);
            break;
          }
          else if(ary[i].children != null ){
            self.aryFindChildre(ary[i].children, attr, id)
          }
        }
      }
    },
    /* * JSON数组去重
    * @param: [array] json Array
    * @param: [string] 唯一的key名，根据此键名进行去重
    */
    uniqueArray(array, key){
      var result = [array[0]];
      for(var i = 1; i < array.length; i++){
        var item = array[i];
        var repeat = false;
        for (var j = 0; j < result.length; j++) {
          if (item[key] == result[j][key]) {
            repeat = true; break;
          }
        } if (!repeat) {
            result.push(item);
          }
      }
      return result;
    },
    dialogMSG(msg, time) {
      const self = this;
        //消息弹框
      this.msgDialogInit = {
        'title': msg ,
      };
      this.msgDialogIsShow = true;
      setTimeout(function(){
        self.msgDialogIsShow = false;
      }, time)
    },
    initFn() {
      switch(this.ajaxSearchType){
        case ajaxTypeMenu :
          this.btnSearch(-1, 0);
            this.columns = [ {
                label: '菜单code',
                prop: 'name',
                width: '300px',
              },
              {
                label: '名称',
                prop: 'displayName',
                minWidth: '250px',
                type: 'template',
                template: 'displayName',
              },
              {
                label: '菜单类型',
                prop: 'target',
              },
              {
                label: '备注',
                prop: 'remark',
                minWidth: '200px',
              }
            ]
            this.dialogInputLabel = {
              "inputName": '菜单code：',
              "inputDisplayName": '菜单名称：',
              "selectTarget": '菜单类型：',
              "inputSort": '排序：',
              "selectType": '类型：'
            }
            //不能出现WPF_9/WPF_10
           this.optType = ['缺省', '地图'];               //菜单类型可选的值
          break;
        case ajaxTypeDataObject :
          this.btnSearch(-1, 0)
          this.columns = [            //列表头部信息
              {
                label: '数据权限code',
                prop: 'name',
                width: '300px',
              },
              {
                label: '名称',
                prop: 'displayName',
                minWidth: '250px',
                type: 'template',
                template: 'displayName',
              },
              // {
              //   label: '菜单类型',
              //   prop: 'target',
              // },
              {
                label: '备注',
                prop: 'remark',
                minWidth: '200px',
              },
          ]
          this.dialogInputLabel = {
                "inputName": '数据权限code：',
                "inputDisplayName": '名称：',
                "selectTarget": '权限类型：',
                "inputSort": '排序：',
                "selectType": '类型：'
              }
          break;
        case ajaxTypeProgram:
          //console.log(this.realDeleteData);
          if(this.$route.params.dataProgramItem != undefined){ // 从缩略图路由传过来
            let dataProgramItem = this.$route.params.dataProgramItem;
            this.previewId = this.$route.params.dataProgramItem.id;
            sessionStorage.setItem('previewId', this.previewId);
            this.dataMenuList.push(dataProgramItem);
          }
          else if(sessionStorage.getItem('previewId') != undefined){ // 本页面刷新
            this.previewId = sessionStorage.getItem('previewId');
            this.$axios.get(this.HOST+'/menu/getNodeChildById?id='
              + this.previewId)
              .then( res => {
              this.dataMenuList.push( res.data );
            })
              .catch( err => {
                //console.log(err);
              })
            ; // 重新执行一遍初始化操作
            /*getNodeChildById( this.previewId ).then(res => {
              this.dataMenuList.push( res.data );
            })*/
          }

          this.columns = [            //列表头部信息
            {
              label: '宫格菜单code',
              prop: 'name',
              width: '300px',
            },
            {
              label: '宫格菜单名称',
              prop: 'displayName',
              minWidth: '250px',
              type: 'template',
              template: 'displayName',
            },
            {
              label: '宫格菜单类型',
              prop: 'target',
            },
            {
              label: '备注',
              prop: 'remark',
              minWidth: '200px',
            },
          ]
          this.dialogInputLabel = {
            "inputName": '宫格菜单code：',
            "inputDisplayName": '宫格菜单名称：',
            "selectTarget": '宫格菜单类型：',
            "inputSort": '排序：',
            "selectType": '类型：'
          }
          break;
      }
    },
  },// end methods
  components: {
    vdialog,
    mustChoseIcon,
    pages,
    picLib,
    linkLib,
    msgDialog,
    isRealDialog,
    SearchPublic
  },
  created() {
    if(this.$route.params.ajaxSearchType != undefined) {
      this.ajaxSearchType = (this.$route.params.ajaxSearchType);
      sessionStorage.setItem('ajaxSearchType',this.$route.params.ajaxSearchType);
    }
    else if(sessionStorage.getItem('ajaxSearchType') != undefined){
      this.ajaxSearchType = parseInt(sessionStorage.getItem('ajaxSearchType'));
    }
    else {
      this.ajaxSearchType = 0;
    }

//    if(this.$route.params.ajaxSearchType == undefined){
//      this.ajaxSearchType = 0;
//    }
//    else {
//      this.ajaxSearchType = this.$route.params.ajaxSearchType;
//    }
    this.initFn()
  },
  watch: {

  }
}
</script>

<style lang="scss" scoped>
  .menu-link-lib {
    width: 100%;
    height: 100%;

    .btn-slot-dialog {
      width: 80px;
      height: 32px;
      padding: 0 10px;
      font-size: 16px;
      margin-right: 10px;
    }
    .wrapper {
      width: 100%;
      height: 100%;
      overflow: hidden;
      padding-bottom: 84px;
      tr:nth-child(even){
        background-color: rgba(51, 51, 51, 0.1);
      }
    }
    .zk-talbe {
      margin-top: 10px;
      width: 100%;
      height: 100%;
      overflow: auto;
      .menu-img {
        width: 20px;
        float:right;
        background:#000;
      }
    }
  }
  .dialog_section {
    margin-left: 14px;
    text-align: left;
    .item-wraper {
      margin-top: 6px;
      clear: both;
    }
    $span_height : 34px;
    $input_select_width: 196px;
    .item {
      line-height: $span_height;
    }
    .input_text, select {
      width: $input_select_width;
      height: $span_height;
      padding: 6px 12px;
      font-size: 14px;
      color: #555;
      border: 1px solid #ccc;
      border-radius: 4px;
      transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
      &:focus {
        border-color: #66afe9;
        outline: 0;
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
      }
    }
  }
  .select-disabled {
    background-color: #ebebe4;
  }
</style>

<style>


  .row-class-name{
  height: 30px !important;
}
.dialog-number {
  width: 60%;
}
.btn-pic-link-dialog {
  height: 30px;
  padding: 0 10px ;
  vertical-align: top;
}
/*.zk-table--row-hover {*/
  /*background-color: #31b0d5 !important;*/
  /*color: #fff;*/
/*}*/
/*.zk-table--level-1-cell,*/
/*.zk-table--level-2-cell,*/
/*.zk-table--level-3-cell,*/
/*.zk-table--level-4-cell,*/
/*.zk-table--level-5-cell,*/
/*.zk-table--level-6-cell {*/
  /*position: relative;*/
/*}*/

/*.zk-table--level-2-cell:before,*/
/*.zk-table--level-3-cell:before,*/
/*.zk-table--level-4-cell:before,*/
/*.zk-table--level-5-cell:before,*/
/*.zk-table--level-6-cell:before {*/
  /*content: '';*/
  /*position: absolute;*/
  /*width: 1px;*/
  /*height: 29px;*/
  /*background-color: rgba(51, 51, 51, .5);*/
  /*border: none;*/
  /*left: -17px;*/
  /*top: -20px;*/
  /*z-index: 1;*/
    /*!*position: absolute;*!*/
    /*!*border: none;*!*/
    /*!*left: -15px;*!*/
    /*!*top: -8px;*!*/
    /*!*z-index: 1;*!*/
/*}*/

/*.zk-table--level-2-cell:after,*/
/*.zk-table--level-3-cell:after,*/
/*.zk-table--level-4-cell:after,*/
/*.zk-table--level-5-cell:after,*/
/*.zk-table--level-6-cell:after {*/
  /*content: '';*/
  /*left: -17px;*/
  /*position: absolute;*/
  /*right: auto;*/
  /*background-color: rgba(51, 51, 51, .5);*/
  /*height: 1px;*/
  /*top: 8px;*/
  /*width: 16px;*/
  /*z-index: 1;*/
/*}*/
/*.zk-table--level-1-cell:before {*/
    /*content: 'Ⅰ';*/
/*}*/
/*.zk-table--level-2-cell:before {*/
    /*content: 'Ⅱ';*/
/*}*/
/*.zk-table--level-3-cell:before {*/
    /*content: 'III';*/
/*}*/
/*.zk-table--level-4-cell:before {*/
    /*content: 'Ⅳ';*/
/*}*/
/*.zk-table--level-5-cell:before {*/
    /*content: 'V';*/
/*}*/
/*.zk-table--level-6-cell:before {*/
    /*content: 'VI';*/
/*}*/
</style>


